<template>
  <div class="fish-production-container">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="渔业产量趋势分析">
          <div ref="productionTrendChart" style="height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="12">
        <a-card title="区域产量分布">
          <div ref="regionalChart" style="height: 400px"></div>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="鱼类产量占比">
          <div ref="speciesChart" style="height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="24">
        <a-card title="产量数据统计">
          <a-table
            :columns="columns"
            :data-source="productionData"
            :pagination="false"
            :loading="loading"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'yearOnYear'">
                <span :style="{ color: getYearOnYearColor(record) }">
                  {{ getYearOnYearChange(record) }}
                </span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import { useFishProductionStore } from '@/stores/fishProductionStore';

const { proxy } = getCurrentInstance();
const productionStore = useFishProductionStore();
const loading = computed(() => productionStore.loading);
const productionData = computed(() => productionStore.productionData);

const productionTrendChart = ref(null);
const regionalChart = ref(null);
const speciesChart = ref(null);

const columns = [
  {
    title: '年份',
    dataIndex: 'year',
    key: 'year',
  },
  {
    title: '总产量 (万吨)',
    dataIndex: 'totalProduction',
    key: 'totalProduction',
    sorter: (a, b) => a.totalProduction - b.totalProduction
  },
  {
    title: '海水产量 (万吨)',
    dataIndex: 'marineProduction',
    key: 'marineProduction',
  },
  {
    title: '淡水产量 (万吨)',
    dataIndex: 'freshwaterProduction',
    key: 'freshwaterProduction',
  },
  {
    title: '同比变化',
    key: 'yearOnYear',
  }
];

const getYearOnYearChange = (record) => {
  const index = productionData.value.findIndex(item => item.year === record.year);
  if (index <= 0) return '—';
  
  const prevYear = productionData.value[index - 1];
  const change = ((record.totalProduction - prevYear.totalProduction) / prevYear.totalProduction * 100).toFixed(2);
  return change > 0 ? `+${change}%` : `${change}%`;
};

const getYearOnYearColor = (record) => {
  const index = productionData.value.findIndex(item => item.year === record.year);
  if (index <= 0) return '';
  
  const prevYear = productionData.value[index - 1];
  const change = record.totalProduction - prevYear.totalProduction;
  return change > 0 ? '#52c41a' : change < 0 ? '#f5222d' : '';
};

onMounted(async () => {
  await productionStore.fetchProductionData();
  const regionalData = await productionStore.fetchRegionalData();
  const speciesData = await productionStore.fetchSpeciesProductionData();
  
  initProductionTrendChart();
  initRegionalChart(regionalData);
  initSpeciesChart(speciesData);
});

const initProductionTrendChart = () => {
  const chartDom = productionTrendChart.value;
  const myChart = proxy.$echarts.init(chartDom);
  
  // const years = productionData.value.map(item => item.year);
  // console.log(years);
  const years = [2021,2022,2023,2024,2025,2026];
  const totalProduction = productionData.value.map(item => item.totalProduction);
  const marineProduction = productionData.value.map(item => item.marineProduction);
  const freshwaterProduction = productionData.value.map(item => item.freshwaterProduction);
  
  const option = {
    title: {
      text: '渔业产量趋势 (2021-2026)',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['总产量', '海水产量', '淡水产量'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: years,
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '产量 (万吨)'
    },
    series: [
      {
        name: '总产量',
        type: 'line',
        data: totalProduction,
        smooth: true,
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(0,0,0,0.3)',
          shadowBlur: 10,
          shadowOffsetY: 8
        },
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '海水产量',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: marineProduction
      },
      {
        name: '淡水产量',
        type: 'line',
        stack: 'Total',
        areaStyle: {},
        emphasis: {
          focus: 'series'
        },
        data: freshwaterProduction
      }
    ]
  };
  
  myChart.setOption(option);
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

const initRegionalChart = (regionalData) => {
  const chartDom = regionalChart.value;
  const myChart = proxy.$echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 万吨 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: regionalData.map(item => item.region)
    },
    series: [
      {
        name: '区域产量',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: regionalData.map(item => ({
          value: item.production,
          name: item.region
        }))
      }
    ]
  };
  
  myChart.setOption(option);
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

const initSpeciesChart = (speciesData) => {
  const chartDom = speciesChart.value;
  const myChart = proxy.$echarts.init(chartDom);
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 万吨 ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: speciesData.map(item => item.species)
    },
    series: [
      {
        name: '鱼类产量',
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: speciesData.map(item => ({
          value: item.production,
          name: item.species
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };
  
  myChart.setOption(option);
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};
</script>

<style scoped>
.fish-production-container {
  padding: 10px 10px 0;
}
</style> 